package api

import (
	"gateway/basic/config"
	user "gateway/basic/proto/userproto"
	"gateway/handler/request"
	"gateway/handler/response"
	"github.com/gin-gonic/gin"
	"log"
)

func UpdateLocation(c *gin.Context) {
	userId := c.GetUint64("userId")
	if userId == 0 {
		response.ParameterError(c, "用户未登录", nil)
		return
	}
	var req request.UpdateLocationReq
	if err := c.ShouldBind(&req); err != nil {
		response.ParameterError(c, "参数格式错误: "+err.Error(), nil)
		return
	}
	if req.Latitude < -90 || req.Latitude > 90 {
		response.ParameterError(c, "纬度须在-90到90之间", nil)
		return
	}
	if req.Longitude < -180 || req.Longitude > 180 {
		response.ParameterError(c, "经度须在-180到180之间", nil)
		return
	}
	res, err := config.UserClient.UpdateLocation(c, &user.UpdateLocationReq{
		UserId:    userId,
		Latitude:  req.Latitude,
		Longitude: req.Longitude,
	})
	if err != nil {
		log.Printf("UpdateLocation: %v", err)
		response.SrvError(c, err.Error(), nil)
		return
	}
	if !res.Success {
		response.SrvError(c, res.Message, nil)
		return
	}
	response.Success(c, res.Message, nil)
}

func GetNearbyUsers(c *gin.Context) {
	userId := c.GetUint64("userId")
	if userId == 0 {
		response.ParameterError(c, "用户未登录", nil)
		return
	}
	var req request.GetNearbyUsersReq
	if err := c.ShouldBindQuery(&req); err != nil {
		response.ParameterError(c, "参数格式错误: "+err.Error(), nil)
		return
	}
	if req.Radius <= 0 {
		req.Radius = 10
	}
	if req.Radius > 50 {
		req.Radius = 50
	}
	if req.Limit <= 0 {
		req.Limit = 20
	}
	res, err := config.UserClient.GetNearbyUsers(c, &user.GetNearbyUsersReq{
		UserId: userId,
		Radius: req.Radius,
		Limit:  req.Limit,
	})
	if err != nil {
		log.Printf("GetNearbyUsers: %v", err)
		response.SrvError(c, err.Error(), nil)
		return
	}
	response.Success(c, "获取附近用户成功", res)
}
